<?php
/**
 * Created by Lgq.
 * User: N
 * Date: 2018/04/11
 * Time: 11:00
 */
namespace common\models;


use Yii;
use yii\base\Model;
use common\models\Models;
use common\help\tools;
use backend\modules\content\models\Sitemodel;
use backend\modules\content\models\Modelfield;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use backend\modules\admin\models\Admin;
use yii\behaviors\TimestampBehavior;
use common\models\OrderLog;
use common\models\User;
use common\models\Attachment;


/**
 * This is the model class for table "sw_order".
 *
 * @property string $catid
 * @property string $siteid
 **/
class Order extends ActiveRecord
{

     /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%order}}';
    }

    /**
    * 验证规则
    */
    public function rules()
    {
        return [
            [['title'],'required','message'=>'不能为空'],
            [['title','content','attaches','m_attaches'],'string','message'=>'格式不正确'],
            [['order_id','from_id','isadmin','area_id','dp_id','type_pid','secret','type_id','status','dispatch_at','deal_at','feedback_at','dealstatus','feedbackstatus','feedstars'],'number','message'=>'格式不正确'],
        ];
    }

//    public function behaviors()
//    {
//
//        return [
//            [
//                'class' => TimestampBehavior::className(),
//                'createdAtAttribute' => 'add_time',// 自己根据数据库字段修改
//                'updatedAtAttribute' => 'last_update', // 自己根据数据库字段修改
//            ],
//        ];
//    }

    public function beforeSave($insert){
        if($insert){
            //插入时补充操作
            $this->status=0;
            $this->created_at = time();
            $this->updated_at = time();

            //将工单的父级分类填入数据库  便于检索
            if($this->type_id >0){
                $typemodel = Otype::find()->where(['type_id' => $this->type_id])->one();
                $this->type_pid = $typemodel->parentid;
            }


        }else{
            //修改时补充操作
            $this->updated_at = time();

        }
        return true;

    }
    public function afterSave($insert,$changedAttributes)
    {
        if($insert || $changedAttributes)
        {
            if($this->area_id){
                $where['area_id'] = $this->area_id;
            }
            $rows = Admin::find()->where($where)->select('userid')->asArray()->all();
            $notice = 1;//默认发送正常；
            if($rows && $this->p_oid <=0){ //存在用户，则发送改地区管理员通知。只发送主工单和独立工单
                foreach($rows as $r){
                    $notice=tools::send_notice(
                        [
                            'order_id'=>$this->order_id,//工单id
                            'title'=>$this->title,//标题
                            'typename'=>$this->typename,
                            'from_id'=>$this->from_id,
                            'to_id'=>$r['userid'],
                            'type_pid'=>$this->type_pid,
                            'type_id'=>1,//通知类型，1派单通知，2任务通知，3站内通知
                            'add_time'=>$this->created_at,
                            'last_update'=>$this->updated_at,
                            'isadmin'=>$this->isadmin,
                            'content'=>$this->content,
                        ]);
                }
            }
            return $notice;
        }

    }



        /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '工单标题',
            'status' => '状态',
            'content' => '工单内容',
            'from_id' => '派单发起人',
            'area_id' => '派单给',
            'type_pid' => '父级分类',
            'type_id' => '工单类型',
            'created_at' => '发单时间',
            'updated_at' => '修改时间',
            'secret' =>'是否保密'
        ];
    }
 /**
     * 是否启用
     */
    public function getSecret()
    {
        if($this->secret=='0')
        {
            return '不保密';
        }
        if($this->secret=='1')
        {
            return '保密';
        }
    }
    public function getTypename()
    {
        if($this->type_id >0){
            $otypemodel = Otype::find()->where(['type_id' => $this->type_id])->one();
            return $otypemodel->type_name;
        }
    }
    
    public function getDepartment()
    {
       return Department::find()->where(['dp_id' => $this->dp_id])->one();
    }
    
    public function getAreaname()
    {
        if($this->area_id >0){
            $areamodel = District::find()->where(['dt_id' => $this->area_id])->one();
            return isset($areamodel->dt_name)?$areamodel->dt_name:'未定义';
        }
    }

    public function getFromname()
    {
        if($this->isadmin == 1){
            $adminmodel = Admin::find()->where(['userid' => $this->from_id])->one();
            return $adminmodel->username;
        }elseif($this->isadmin == 0){
            $usermodel = User::find()->where(['id' => $this->from_id])->one();
            return $usermodel->realname;
        }
    }

    public function getTel()
    {
        if($this->isadmin == 1){
            $adminmodel = Admin::find()->where(['userid' => $this->from_id])->one();
            return $adminmodel->tel?mb_substr($adminmodel->tel,0,5).'*****':'--';
        }elseif($this->isadmin == 0){
            $usermodel = User::find()->where(['id' => $this->from_id])->one();
            return $usermodel->tel?mb_substr($usermodel->tel,0,5).'*****':'--';
        }
    }

    public function getAddress()
    {
        if($this->isadmin == 1){
            $adminmodel = Admin::find()->where(['userid' => $this->from_id])->one();
            return '';
        }elseif($this->isadmin == 0){
            $usermodel = User::find()->where(['id' => $this->from_id])->one();
            return $usermodel->info;
        }
    }

    /*public function getToname()
    {

            $usermodel = User::find()->where(['id' => $this->to_id])->one();
            return $usermodel->realname;

    }*/

    public function getStatusnow()
    {
        switch($this->status){
            case -1:
                return '已删除';
                break;
            case 0:
                return '未派单';
                break;
            case 1:
                if($this->dealstatus){
                    return '已派单,已处置';
                }
                return '已派单,未处置';
                break;
            case 2:
                if($this->feedbackstatus){
                    return '已完结,已反馈';
                }
                return '已完结,未反馈';
                break;
            case 10:
                return '疑难问题';
                break;
            default:
                return '状态异常';
        }

    }
    public function getBtn()
    {
        switch($this->status){
            case 1:
                return '点击处置';
                break;
            case 0:
                return '派单';
                break;
            default:
                return '查看';
        }
    }

    public function getFeedstarname()
    {
        switch($this->feedstars){
            case 0:
                return '未反馈';
                break;
            case 1:
                return '满意';
                break;
            case 2:
                return '不满意';
                break;
            default:
                return '状态异常';
        }

    }

   /* public function getNtype()
    {
        return $this->hasOne(Ntype::className(), ['type_id' => 'type_id']);
    }*/

    /**
     * 获取附件列表
     */
    public function getAttachlist()
    { 
        if($this->attaches)
        {
            $attachids=explode(',',$this->attaches);
            foreach($attachids as $tt)
            {
                if($tt)
                    $temps[]=$tt;
            }
            $astr=implode(',',$temps);
            $attaches=Attachment::find('')->where("status=0 and aid in ({$astr})")->orderBy('aid desc')->all();
            return $attaches;
        }
        else
        {
            return [];
        }
    }

    /**
     * 获取管理员上传的图片附件信息
     * @return array|ActiveRecord[]
     */
    public function getM_attachlist($m_attaches='')
    {
        if($m_attaches) $this->m_attaches = $m_attaches;
        if($this->m_attaches)
        {
            $attachids=explode(',',$this->m_attaches);
            foreach($attachids as $tt)
            {
                if($tt)
                    $temps[]=$tt;
            }
            $astr=implode(',',$temps);
            $attaches=Attachment::find('')->where("status=0 and aid in ({$astr})")->orderBy('aid desc')->all();
            return $attaches;
        }
            return [];

    }

    /**
     * 计算剩余天时分。
     * $dispatchtime string 终止日期的Unix时间
     * @author lgq
     * @version 2018-04-18
     */
    function getYipaidantime()
    {
        $dispatchtime = $this->dispatch_at;
        if ($dispatchtime >= time()) {
            return '0天0小时0分钟';
        }

        // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
        $time = time() - $dispatchtime;

        $days = 0;
        if ($time >= 86400) { // 如果大于1天
            $days = (int)($time / 86400);
            $time = $time % 86400; // 计算天后剩余的毫秒数
        }

        $xiaoshi = 0;
        if ($time >= 3600) { // 如果大于1小时
            $xiaoshi = (int)($time / 3600);
            $time = $time % 3600; // 计算小时后剩余的毫秒数
        }

        $fen = (int)($time / 60); // 剩下的毫秒数都算作分

        return $days.'天'.$xiaoshi.'小时'.$fen.'分钟';
    }

    /**
     * 获取分类等级
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    public static function get_level($id,$array=array(),$i=0)
    {
        foreach($array as $n=>$value){
            if($value['type_id'] == $id)
            {
                if($value['parentid']== '0') return $i;
                $i++;
                return self::get_level($value['parentid'],$array,$i);
            }
        }

    }

    /**
     * 获取某区县满意度
     * @param int $area_id 区县ID
     * @return int $return 满意度
     */
    public static function get_satisfaction($area_id)
    {
        $score = Order::find()->select('feedstars')->where(['area_id'=>$area_id])->asArray()->all();
        $all_num = count($score);
        $satisfaction = 0;
        if($all_num)
        {
            $num = 0;
            foreach($score as $key=>$val)
            {
                if($val['feedstars'] == 1 || $val['feedstars'] == 0)
                {
                    $num++;
                }
            }
            $satisfaction = ($num/$all_num)*100;
        }
        return $satisfaction;
    }

    /**
     * 获取关联工单。主工单则获取所有附属工单，附属工单则只获取主工单
     * @return array|ActiveRecord[]
     */
    public function getreleted(){
        if($this->p_oid<0){ //独立工单
            return [];
        }elseif($this->p_oid==0){//主工单,查找所有附属工单
            $where = ['p_oid'=>$this->order_id];
        }else{ //附属工单，查找主工单
            $where['order_id']= $this->p_oid;//
        }
        $rows = Order::find()->where($where)->select('order_id,title,')->asArray()->all();
        return $rows?$rows:[];
    }

    /**
     * 获取工单类型，若有父级，则继续获取父级类型名称
     */
    public static function getAlltype($type_id)
    {
        $type_name = array();
        $type = Otype::find()->where(['type_id'=>$type_id])->one();
        
        if($type->parentid)
        {
            $type_p=Order::getAlltype($type->parentid);
            foreach($type_p as $key=>$val)
            {
                $type_name[] = $val;
            }
            
        }
        $type_name[] = $type->type_name;
        
        ksort($type_name);
        return $type_name;
    }
}